from user.models import User, Empower
from pms.common.utils import has_permissions, has_one_of_permissions
from pms.common.views import PermissionDeny


def get_pids_by_rid(rid):
    return [int(x['pid']) for x in Empower.objects.filter(rid=rid).order_by('pid_id').values('pid')]


def has_system_permissions(uid, permissions):
    """ 用户 uid 是否拥有 permissions 中的所有权限 """
    user = User.objects.get(id=uid)
    role = user.rid
    empowered_permissions = get_pids_by_rid(role.id)
    if 1 in empowered_permissions:  # 1-所有权限
        return True
    return has_permissions(permissions, empowered_permissions)


def has_one_of_system_permissions(uid, permissions):
    """ 用户 uid 是否拥有 permissions 中的至少一个权限 """
    user = User.objects.get(id=uid)
    role = user.rid
    empowered_permissions = get_pids_by_rid(role.id)
    if 1 in empowered_permissions:  # 1-所有权限
        return True
    else:
        return has_one_of_permissions(permissions, empowered_permissions)


def assert_system_permissions(uid, permissions):
    """ 若用户 uid 在部门 did 中没有拥有 permissions 中的所有权限则抛出 PermissionDeny 错误 """
    if not has_system_permissions(uid, permissions):
        raise PermissionDeny


def assert_one_of_system_permissions(uid, permissions):
    """ 若用户 uid 在部门 did 中没有拥有 permissions 中的至少一个权限则抛出 PermissionDeny 错误 """
    if not has_one_of_system_permissions(uid, permissions):
        raise PermissionDeny
